<template>
  <div class="AddFreightModel">
    <div class="cus-title">
      <h4
        v-if="
          activeModel === '1' &&
            status == 'edit'
        "
      >
        编辑快递
      </h4>
      <h4
        v-if="
          activeModel === '2' &&
            status == 'edit'
        "
      >
        编辑同城
      </h4>
      <h4 v-if="status == false">新增运费模板</h4>
    </div>
    <div class="tabspane">
      <el-tabs v-model="activeModel">
        <el-tab-pane
          label="云仓物流"
          name="1"
          :disabled="activeModel=='2'"
        >
          <div>模板配置</div>
          <el-form ref="formsk" :model="kBindForm" :rules="pattern">
            <el-form-item
              label="模板名称"
              prop="templateName"
              class="templateName"
            >
              <el-col :span="20">
                <el-input
                  v-model="kBindForm.templateName"
                  maxlength="20"
                  class="cus-input"
                  placeholder="输入模板名称"
                />
              </el-col>
            </el-form-item>
            <el-form-item label="计费方式">
              <el-col :span="20">
                <el-radio
                  v-model="kBindForm.billingMethod"
                  label="0"
                  @change="handelChangeJffs"
                >按件量</el-radio>
                <el-radio
                  v-model="kBindForm.billingMethod"
                  label="1"
                  @change="handelChangeJffs"
                >按重量</el-radio>
              </el-col>
            </el-form-item>
            <el-form-item label="配送区域" required>
              <el-col :span="22">
                <div
                  v-for="(val, index) in kBindForm.bistributionArea"
                  :key="index"
                  class="cus-area"
                >
                  <div class="left">
                    <p>可配送区域</p>
                    <p>
                      <!-- 可配送区域 -->
                      <span class="addressName">{{ val.addressName }}</span>
                      <span>
                        <el-button
                          type="text"
                          @click="handelUpdateArea(index)"
                        >修改</el-button>
                        <el-button
                          type="text"
                          @click="handelDel(index)"
                        >删除</el-button>
                      </span>
                    </p>
                  </div>
                  <div class="right">
                    <table v-if="kBindForm.billingMethod == '1'">
                      <tr>
                        <td>首重(kg)</td>
                        <td>运费(元)</td>
                        <td>续重(kg)</td>
                        <td>续费(元)</td>
                      </tr>
                      <tr>
                        <td>
                          <el-form-item
                            :prop="`bistributionArea.${index}.theFirstPiece`"
                            :rules="{
                              required: true,
                              message: '不能为空',
                              trigger: 'blur'
                            }"
                          >
                            <el-input-number
                              v-model="val.theFirstPiece"
                              :controls="false"
                              :precision="2"
                              :min="0.01"
                              :max="999"
                              style="width:100px"
                            />
                          </el-form-item>
                        </td>
                        <td>
                          <el-form-item
                            :prop="`bistributionArea.${index}.piece`"
                            :rules="{
                              required: true,
                              message: '不能为空',
                              trigger: 'blur'
                            }"
                          >
                            <el-input-number
                              v-model="val.piece"
                              :controls="false"
                              :precision="2"
                              :min="0.01"
                              :max="100000"
                              style="width:100px"
                            />
                          </el-form-item>
                        </td>
                        <td>
                          <el-form-item
                            :prop="`bistributionArea.${index}.ahead`"
                            :rules="{
                              required: true,
                              message: '不能为空',
                              trigger: 'blur'
                            }"
                          >
                            <el-input-number
                              v-model="val.ahead"
                              :controls="false"
                              :precision="2"
                              :min="0.01"
                              :max="999"
                              style="width:100px"
                            />
                          </el-form-item>
                        </td>
                        <td>
                          <el-form-item
                            :prop="`bistributionArea.${index}.charge`"
                            :rules="{
                              required: true,
                              message: '不能为空',
                              trigger: 'blur'
                            }"
                          >
                            <el-input-number
                              v-model="val.charge"
                              :controls="false"
                              :precision="2"
                              :min="0"
                              :max="9999"
                              style="width:100px"
                            />
                          </el-form-item>
                        </td>
                      </tr>
                    </table>

                    <table v-if="kBindForm.billingMethod == '0'">
                      <tr>
                        <td>首件(件)</td>
                        <td>运费(元)</td>
                        <td>续件(件)</td>
                        <td>续费(元)</td>
                      </tr>
                      <tr>
                        <td>
                          <el-form-item
                            :prop="`bistributionArea.${index}.theFirstPiece`"
                            :rules="{
                              required: true,
                              message: '不能为空',
                              trigger: 'blur'
                            }"
                          >
                            <el-input-number
                              v-model="val.theFirstPiece"
                              :controls="false"
                              :precision="0"
                              :min="1"
                              :max="1000"
                              style="width:100px"
                            />
                          </el-form-item>
                          <!-- <el-input v-model="val.theFirstPiece" /> -->
                        </td>
                        <td>
                          <el-form-item
                            :prop="`bistributionArea.${index}.piece`"
                            :rules="{
                              required: true,
                              message: '不能为空',
                              trigger: 'blur'
                            }"
                          >
                            <el-input-number
                              v-model="val.piece"
                              :controls="false"
                              :precision="2"
                              :min="0"
                              :max="9999"
                              style="width:100px"
                            />
                          </el-form-item>
                          <!-- <el-input v-model="val.piece" /> -->
                        </td>
                        <td>
                          <el-form-item
                            :prop="`bistributionArea.${index}.ahead`"
                            :rules="{
                              required: true,
                              message: '不能为空',
                              trigger: 'blur'
                            }"
                          >
                            <el-input-number
                              v-model="val.ahead"
                              :controls="false"
                              :precision="0"
                              :min="1"
                              :max="1000"
                              style="width:100px"
                            />
                          </el-form-item>
                          <!-- <el-input v-model="val.ahead" /> -->
                        </td>
                        <td>
                          <el-form-item
                            :prop="`bistributionArea.${index}.charge`"
                            :rules="{
                              required: true,
                              message: '不能为空',
                              trigger: 'blur'
                            }"
                          >
                            <el-input-number
                              v-model="val.charge"
                              :controls="false"
                              :precision="2"
                              :min="0"
                              :max="9999"
                              style="width:100px"
                            />
                          </el-form-item>
                          <!-- <el-input v-model="val.charge" /> -->
                        </td>
                      </tr>
                    </table>
                  </div>
                </div>
                <div class="cus-btn-footer">
                  <el-button
                    type="primary"
                    @click="handelAddArea"
                  >添加配送区域</el-button>
                </div>
                <div class="cus-btn-submit">
                  <el-button
                    type="primary"
                    :loading="butloading"
                    @click="handelFormSubmitk('K')"
                  >提交</el-button>
                </div>
              </el-col>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <!--***
        ************
        ***************同城配送*
        **********************
        ***********-->
        <el-tab-pane
          label="同城配送"
          name="2"
          :disabled="activeModel=='1'"
        >
          <div>模板配置</div>
          <el-form ref="formst" :model="tBindForm" :rules="pattern">
            <el-form-item
              label="模板名称"
              prop="templateName"
              class="templateName"
            >
              <el-col :span="20">
                <el-input
                  v-model="tBindForm.templateName"
                  maxlength="20"
                  class="cus-input"
                  placeholder="输入模板名称"
                />
              </el-col>
            </el-form-item>
            <el-form-item label="计费方式">
              <el-col :span="20">
                <div class="JFFS">
                  <el-radio
                    v-model="tBindForm.billingMethod"
                    label="1"
                    @change="handelpisQy"
                  >按区域配送</el-radio>
                  <p>配送区域内商品不会计算距离，按区域收取固定配送费。</p>
                </div>
                <div class="JFFS">
                  <el-radio
                    v-model="tBindForm.billingMethod"
                    label="2"
                    @change="handelpisQy"
                  >按距离配送</el-radio>
                  <p v-if="tBindForm.billingMethod == '2'">
                    因考虑实际送货路况，配送费计算按步行距离，非地图直线距离。
                  </p>
                </div>
              </el-col>
            </el-form-item>
            <el-form-item label="配送区域">
              <el-col :span="22">
                <div v-if="tBindForm.billingMethod == '1'" class="PSQY">
                  <p>
                    <el-form-item prop="distributionArea.kilometers">
                      <el-input-number
                        v-model="tBindForm.distributionArea.kilometers"
                        :controls="false"
                        :precision="2"
                        :min="0.01"
                        :max="999"
                        style="width:100px"
                      />
                      <span>公里内按</span>
                    </el-form-item>
                  </p>
                  <p>
                    <el-form-item prop="distributionArea.charge">
                      <el-input-number
                        v-model="tBindForm.distributionArea.charge"
                        :controls="false"
                        :precision="2"
                        :min="0.01"
                        :max="10000"
                        style="width:100px"
                      />
                      <span>元收费。</span>
                    </el-form-item>
                  </p>
                </div>
                <div v-if="tBindForm.billingMethod == '2'" class="PSQY">
                  <p>
                    <el-form-item prop="distributionArea.kilometers">
                      <el-input-number
                        v-model="tBindForm.distributionArea.kilometers"
                        :precision="2"
                        :controls="false"
                        :min="0.01"
                        :max="999"
                        style="width:100px"
                      /><span>公里内按</span>
                    </el-form-item>
                  </p>
                  <p>
                    <el-form-item prop="distributionArea.charge">
                      <el-input-number
                        v-model="tBindForm.distributionArea.charge"
                        :controls="false"
                        :precision="2"
                        :min="0.01"
                        :max="100000"
                        style="width:100px"
                      /><span>元收费，每增加</span>
                    </el-form-item>
                  </p>
                  <p>
                    <el-form-item prop="distributionArea.iKilometers">
                      <el-input-number
                        v-model="tBindForm.distributionArea.iKilometers"
                        :controls="false"
                        :precision="2"
                        :min="0.01"
                        :max="999"
                        style="width:100px"
                      /><span>公里费用增加</span>
                    </el-form-item>
                  </p>
                  <p>
                    <el-form-item prop="distributionArea.iCharge">
                      <el-input-number
                        v-model="tBindForm.distributionArea.iCharge"
                        :controls="false"
                        :precision="2"
                        :min="0.01"
                        :max="100000"
                        style="width:100px"
                      />
                      <span>元</span>
                    </el-form-item>
                  </p>
                  <p>
                    <el-form-item
                      prop="distributionArea.support"
                      class="distributionArea"
                    ><span>支持区域</span>
                      <el-input-number
                        v-model="tBindForm.distributionArea.support"
                        :precision="2"
                        :controls="false"
                        :min="1"
                        :max="9999"
                        style="width:100px"
                      />
                      <span>公里</span>
                    </el-form-item>
                  </p>
                </div>
                <!--                <div class="MapArea">
                  <baidu-map
                    :center="center"
                    :zoom="zoom"
                    class="baidu-map"
                    scroll-wheel-zoom
                    @ready="handelReady"
                    @dblclick="handelMap"
                    @click="handelBapClick"
                  >
                    <bm-circle
                      :center="circlePath.center"
                      :radius="circlePath.radius"
                      stroke-color="blue"
                      :stroke-opacity="0.5"
                      :stroke-weight="2"
                      :editing="false"
                    />
                    <bm-walking
                      :start="walkingstart"
                      :end="walkingend"
                      :auto-viewport="true"
                      :location="locawalking"
                    />
                  </baidu-map>
                </div>-->
              </el-col>
            </el-form-item>
            <el-form-item label="额外收费" prop="weight.type">
              <el-col :span="20">
                <el-col :span="24">
                  <el-col :span="3">
                    <el-radio v-model="tBindForm.weight.type" label="0">续重收费</el-radio>
                  </el-col>
                  <el-col :span="12">
                    <div class="XZSF">
                      <p>
                        <el-form-item prop="weight.weightExtra">
                          <el-input-number
                            v-model="tBindForm.weight.weightExtra"
                            :controls="false"
                            :disabled="tBindForm.weight.type!=0"
                            :precision="2"
                            :min="0"
                            :max="999"
                          /><span>kg内不收取额外费用，每超出</span>
                        </el-form-item>
                      </p>
                      <p>
                        <el-form-item prop="weight.weightAddCharges">
                          <el-input-number
                            v-model="tBindForm.weight.weightAddCharges"
                            :controls="false"
                            :disabled="tBindForm.weight.type!=0"
                            :precision="2"
                            :min="0"
                            :max="999"
                          /><span>kg增加收费</span>
                        </el-form-item>
                      </p>
                      <p>
                        <el-form-item prop="weight.weightIncrease">
                          <el-input-number
                            v-model="tBindForm.weight.weightIncrease"
                            :controls="false"
                            :disabled="tBindForm.weight.type!=0"
                            :precision="2"
                            :min="0.01"
                            :max="100000"
                          /><span>元</span>
                        </el-form-item>
                      </p>
                    </div>
                  </el-col>
                </el-col>
                <el-col :span="24">
                  <el-col :span="3">
                    <el-radio v-model="tBindForm.weight.type" label="1">件数收费</el-radio>
                  </el-col>
                  <el-col :span="12">
                    <div class="XZSF">
                      <p>
                        <el-form-item prop="weight.pieceExtra">
                          <el-input-number
                            v-model="tBindForm.weight.pieceExtra"
                            :controls="false"
                            :disabled="tBindForm.weight.type!=1"
                            :precision="2"
                            :min="0"
                            :max="999"
                          /><span>件内不收取额外费用，每超出</span>
                        </el-form-item>
                      </p>
                      <p>
                        <el-form-item prop="weight.pieceAddCharges">
                          <el-input-number
                            v-model="tBindForm.weight.pieceAddCharges"
                            :controls="false"
                            :disabled="tBindForm.weight.type!=1"
                            :precision="2"
                            :min="0"
                            :max="999"
                          /><span>件增加收费</span>
                        </el-form-item>
                      </p>
                      <p>
                        <el-form-item prop="weight.pieceIncrease">
                          <el-input-number
                            v-model="tBindForm.weight.pieceIncrease"
                            :controls="false"
                            :disabled="tBindForm.weight.type!=1"
                            :precision="2"
                            :min="0.01"
                            :max="100000"
                          /><span>元</span>
                        </el-form-item>
                      </p>
                    </div>
                  </el-col>
                </el-col>
              </el-col>
            </el-form-item>
            <el-form-item label="送达时间">
              <div style="display: flex;flex-wrap: wrap;">
                <el-form-item prop="fastTime">
                  <el-input-number
                    v-model="tBindForm.fastTime"
                    placeholder="最快送达时间"
                    :controls="false"
                    :precision="0"
                    :min="0"
                    :max="24"
                  />
                </el-form-item>
                <span style="margin-left:100px">至</span>
                <el-form-item prop="slowTime">
                  <el-input-number
                    v-model="tBindForm.slowTime"
                    placeholder="最慢送达时间"
                    :controls="false"
                    :precision="0"
                    :min="0"
                    :max="24"
                  />
                  <span style="margin-left:100px">小时</span>
                </el-form-item>
              </div>
            </el-form-item>
            <el-form-item label="配送方式">
              <el-col :span="22">
                <div class="PSFS">
                  <el-checkbox
                    v-model="tBindForm.distri"
                    true-label="1"
                    false-label="0"
                  >支持预约</el-checkbox>
                  <el-checkbox
                    v-model="tBindForm.butionMode"
                    true-label="1"
                    false-label="0"
                    @change="handelCheckChange"
                  >支持加急</el-checkbox>
                </div>
                <div v-if="tBindForm.distri == '1'" class="PSFS">
                  <div class="YYTS">
                    <div style="display:flex">
                      <span class="title-yyts">可预约天数:</span>
                      <el-form-item prop="mana">
                        <el-input-number
                          v-model="tBindForm.mana"
                          :controls="false"
                          :precision="0"
                          :min="1"
                          :max="10"
                          placeholder="输入天数"
                        />
                        <span class="mleft">元</span>
                      </el-form-item>
                    </div>
                    <p style="margin-top: 22px;">
                      用户可以选择送达的最晚日期。可预约天数为3天，那用户下单时，在选择预约时间为当前时间的后三天。
                    </p>
                  </div>
                </div>
                <div v-if="tBindForm.distri == '1'" class="PSFS">
                  <div
                    v-for="(item, index) in tBindForm.timePeriod"
                    :key="index"
                    class="SHDUAN"
                  >
                    <div class="left">
                      <span class="title-yyts">时间段{{ index + 1 }}:</span>
                      <el-form-item
                        :prop="`timePeriod.${index}.startTime`"
                        :rules="[
                          {
                            required: true,
                            message: '请输入开始时间段',
                            trigger: ['change', 'blur']
                          },
                          {
                            validator: vastartTime,
                            index: index
                          }
                        ]"
                      >
                        <el-time-select
                          v-model="item.startTime"
                          placeholder="起始时间"
                          default-value="08:30"
                          :picker-options="{
                            start: '01:00',
                            step: '00:30',
                            end: '24:00',
                            minTime:
                              tBindForm.timePeriod[
                                index > 0 ? index - 1 : index
                              ].entTime
                          }"
                          @change="handelTime(item, index)"
                        />
                      </el-form-item>
                      <span class="mleft">————</span>
                      <el-form-item
                        :prop="`timePeriod.${index}.entTime`"
                        :rules="[
                          {
                            required: true,
                            message: '请输入结束时间段',
                            trigger: ['change', 'blur']
                          }
                        ]"
                      >
                        <el-time-select
                          v-model="item.entTime"
                          placeholder="结束时间"
                          :picker-options="{
                            start: '01:00',
                            step: '00:30',
                            end: '24:00',
                            minTime: item.startTime
                          }"
                        />
                      </el-form-item>

                      <div class="ewfy">
                        <el-form-item
                          class="extraCharge"
                          :prop="`timePeriod.${index}.extraCharge`"
                          :rules="[
                            {
                              required: true,
                              message: '请输入额外费用',
                              trigger: 'blur'
                            }
                          ]"
                        >
                          <span class="mleft">增加额外费用:</span>
                          <el-input-number
                            v-model="item.extraCharge"
                            :controls="false"
                            :precision="2"
                            :min="0.01"
                            :max="100000"
                            placeholder="金额"
                            class="inputNumber"
                          />
                          <span>元</span>
                        </el-form-item>
                      </div>
                    </div>
                    <el-button
                      v-if="tBindForm.timePeriod.length > 1"
                      type="text"
                      style="color:red;z-index:1000"
                      @click="tBindForm.timePeriod.splice(index, 1)"
                    >
                      删除
                    </el-button>
                  </div>
                  <div class="SHDUAN">
                    <el-button
                      v-if="tBindForm.distri == '1'"
                      class="add_button"
                      :disabled="tBindForm.timePeriod.length == 20"
                      type="primary"
                      plain
                      @click="handelAddTime"
                    >添加时间段</el-button>
                  </div>
                </div>
                <div v-if="tBindForm.butionMode == '1'" class="PSFS">
                  <div class="YYTS">
                    <div style="display:flex">
                      <span class="title-yyts">加急费用:</span>
                      <div>
                        <div
                          v-for="(item, index) in tBindForm.speedUp.urgents"
                          :key="index"
                          style="margin-bottom:15px"
                        >
                          <el-form-item
                            :prop="`speedUp.urgents.${index}`"
                            :rules="{
                              required: true,
                              message: '请输入加急费用',
                              trigger: 'blur'
                            }"
                          >
                            <el-input-number
                              v-model="tBindForm.speedUp.urgents[index]"
                              :controls="false"
                              :precision="2"
                              :min="0.01"
                              :max="100000"
                              placeholder="输入金额"
                            />
                            <span
                              class="mleft"
                              style="margin-left:100px"
                            >元</span>
                          </el-form-item>

                          <!--                          <el-button
                            v-if="index == tBindForm.speedUp.urgents.length - 1"
                            class="tjje"
                            type="text"
                            :disabled="tBindForm.speedUp.urgents.length == 20"
                            @click="tBindForm.speedUp.urgents.push('')"
                          >添加金额</el-button>-->
                          <!--                          <el-button
                            v-if="tBindForm.speedUp.urgents.length > 1"
                            type="text"
                            style="color:red;"
                            @click="tBindForm.speedUp.urgents.splice(index, 1)"
                          >删除</el-button>-->
                        </div>
                      </div>
                    </div>
                    <p>在基础费用之上，额外增加的加急费用。</p>
                  </div>
                </div>
                <div v-if="tBindForm.butionMode == '1'" class="PSFS">
                  <div class="YYTS">
                    <div style="display:flex">
                      <span class="title-yyts">最快加急时间:</span>
                      <el-form-item prop="speedUp.timeInterval">
                        <el-input-number
                          v-model="tBindForm.speedUp.timeInterval"
                          style="width: 200px;"
                          :controls="false"
                          :precision="0"
                          :min="1"
                          :max="24"
                          placeholder="输入时间"
                        />
                      </el-form-item>
                    </div>

                    <p style="margin-top: 22px;">可加急送达的最快时间</p>
                    <p class="JSAOa">
                      例：1、用户13点下单，最快加急时间为4小时，那么给用户显示的最早加急时间为17点，如果该时间超出门店最晚营业时间，那么就不显示加急。
                    </p>
                    <p class="JSAOb">
                      2、如果加急间隔时间为2小时，那么给用户显示的最晚加急时间为17:00-19:00。
                    </p>
                  </div>
                </div>
                <div v-if="tBindForm.butionMode == '1'" class="PSFS">
                  <div class="YYTS">
                    <div style="display:flex">
                      <span class="title-yyts">加急时间间隔:</span>
                      <el-form-item prop="speedUp.urgentTime">
                        <el-input-number
                          v-model="tBindForm.speedUp.urgentTime"
                          :controls="false"
                          :precision="0"
                          :min="1"
                          :max="24"
                          placeholder="输入时间"
                        />
                        <span class="mleft">小时</span>
                      </el-form-item>

                    </div>

                    <p style="margin-top: 22px;">通过间隔时间计算可加急配送的最晚时间。</p>
                  </div>
                </div>
              </el-col>
            </el-form-item>
            <el-form-item class="cus-footer">
              <el-button
                type="primary"
                class="cus-btn-submit"
                :loading="butloading"
                @click="handelFormSubmitt('T')"
              >提交</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 添加配送区域 -->
    <el-dialog
      :visible.sync="visible"
      :close-on-click-modal="false"
      width="600px"
      :before-close="handelBefore"
    >
      <el-select
        v-model="province"
        size="medium"
        class="ele-select"
        multiple
        clearable
        collapse-tags
        :loading="seloading"
        @change="handelChange"
      >
        <el-option
          v-for="(item, indx) in options"
          :key="indx"
          :value="item.id"
          :label="item.name"
        />
      </el-select>
      <div slot="footer">
        <el-button type="primary" @click="handelSubmit()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCityList } from '@/api/auth'
import {
  FreightTemplateAdd,
  addSameCityAdd,
  FreightTemplatekEdit,
  FreightTemplatetEdit
} from '@/api/customAPI/shop/FreightTemplate'
/** 新增运费模板 */
export default {
  name: 'AddFreightModel',
  data() {
    return {
      butloading: false,
      seloading: false,
      visible: false,
      activeModel: '1',
      province: null,
      options: [],
      // 可配送区域
      region: [],
      selectCheck: [],
      // true 添加，false 修改
      isTrue: true,
      // 添加配送区域用
      kBindForm: {
        shopId: localStorage.getItem('shopId'),
        billingMethod: '1',
        templateName: '',
        bistributionArea: []
      },
      // 添加同城
      tBindForm: {
        shopId: localStorage.getItem('shopId'),
        templateName: '',
        billingMethod: '1',
        distributionArea: {
          kilometers: '',
          charge: '',
          iKilometers: '',
          iCharge: '',
          support: ''
        },
        weight: {
          extra: '',
          addCharges: '',
          increase: '',
          type: '0',
          weightExtra: '',
          weightAddCharges: '',
          weightIncrease: '',
          pieceExtra: '',
          pieceAddCharges: '',
          pieceIncrease: ''
        },
        distri: '1',
        butionMode: '0',
        mana: '',
        timePeriod: [
          {
            startTime: '',
            entTime: '',
            extraCharge: ''
          }
        ],
        speedUp: {
          timeInterval: '',
          urgentTime: '',
          urgents: [''],
          urgent: ''
        },
        slowTime: 0,
        fastTime: 0
      },
      pattern: {
        templateName: [
          { required: true, message: '请输入模板名称', trigger: 'blur' }
        ],
        'distributionArea.kilometers': [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        'distributionArea.charge': [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        'distributionArea.iKilometers': [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        'distributionArea.iCharge': [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        'distributionArea.support': [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        'weight.weightExtra': [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        'weight.weightAddCharges': [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        'weight.weightIncrease': [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        'weight.pieceExtra': [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        'weight.pieceAddCharges': [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        'weight.pieceIncrease': [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        slowTime: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { validator: this.slowTime, trigger: 'blur' }
        ],
        fastTime: [{ required: true, message: '不能为空', trigger: 'blur' }],
        mana: [{ required: true, message: '可预约天数不能为空', trigger: 'blur' }],
        'speedUp.timeInterval': [{ required: true, message: '最快加急时间不能为空', trigger: 'blur' }],
        'speedUp.urgentTime': [{ required: true, message: '加急时间间隔不能为空', trigger: 'blur' }]
      }
    }
  },
  /* mounted() {
    this.getCity(true)
  },
  activated() {
    this.getCity(true)
  },*/
  created() {
    const params = this.$dd(this.$route.query.p)
    console.log(params)
    this.activeModel = params.activeModel
    this.status = params.status
    this.getCity(true)
  },
  methods: {
    handelpisQy(v) {
      if (v === '1' && !this.circlePath.radius) {
        this.circlePath.radius = 10
      } else if (v === '2' && !this.circlePath.radius) {
        this.circlePath.radius = 1000
      }
    },
    handelChangeJffs() {
      this.kBindForm.bistributionArea.forEach(inf => {
        inf.charge = ''
        inf.ahead = ''
        inf.piece = ''
        inf.theFirstPiece = ''
      })
    },
    handelTime(item, index) {
      item.entTime = ''
    },
    /** 编辑时初始化 */
    loadding() {
      const params = this.$dd(this.$route.query.p)
      console.log(params)
      if (
        params.status === 'edit' ||
        params.status === 'copy'
      ) {
        switch (params.activeModel) {
          case '1':
            this.kBindForm.templateName = params.row.name
            this.kBindForm.billingMethod = params.row.payType.toString()
            this.kBindForm.bistributionArea = JSON.parse(
              params.row.expressTemplate
            )
            if (this.kBindForm.bistributionArea.length > 0) {
              this.kBindForm.bistributionArea.forEach(inf => {
                var list = []
                var region = inf.region.split(',')
                this.options.forEach(val => {
                  region.forEach(res => {
                    if (val.id.toString() === res) {
                      list.push(val.name)
                    }
                  })
                })
                inf.region = region
                inf.addressName = list.toString()
              })
            }
            console.log(this.kBindForm.bistributionArea, 'this.kBindForm.bistributionArea')
            break
          case '2':
            this.tBindForm.templateID = params.templateID
            this.tBindForm.templateName = params.row.name
            this.tBindForm.billingMethod = params.row.payType.toString()
            this.tBindForm.distri = params.row.canAppointment.toString()
            this.tBindForm.butionMode = params.row.canUrgent.toString()
            if (params.row.payType.toString() === '1') {
              this.tBindForm.distributionArea.kilometers = params.row.deliveryRange
              this.tBindForm.distributionArea.charge = params.row.fixedPay
            }
            if (params.row.payType.toString() === '2') {
              this.tBindForm.distributionArea.kilometers = params.row.sameCityFirstUnit
              this.tBindForm.distributionArea.charge = params.row.sameCityFirstUnitPay
              this.tBindForm.distributionArea.iKilometers = params.row.sameCityAfterUnit
              this.tBindForm.distributionArea.iCharge = params.row.sameCityAfterUnitPay
              this.tBindForm.distributionArea.support = params.row.deliveryRange
            }
            this.tBindForm.mana = params.row.canAppointmentType
            if (params.row.additionalPayType == 0) {
              this.tBindForm.weight.type = '0'
              this.tBindForm.weight.weightExtra = params.row.weight
              this.tBindForm.weight.weightAddCharges = params.row.weightAfterUnit
              this.tBindForm.weight.weightIncrease = params.row.weightAfterUnitPay
            } else if (params.row.additionalPayType == 1) {
              this.tBindForm.weight.type = '1'
              this.tBindForm.weight.pieceExtra = params.row.weight
              this.tBindForm.weight.pieceAddCharges = params.row.weightAfterUnit
              this.tBindForm.weight.pieceIncrease = params.row.weightAfterUnitPay
            }
            /* this.tBindForm.weight.extra = params.row.weight
            this.tBindForm.weight.addCharges = params.row.weightAfterUnit
            this.tBindForm.weight.increase = params.row.weightAfterUnitPay*/
            // urgentPay 加急
            // earlyUrgentPay 最快
            // lastUrgentPay 间隔
            this.tBindForm.speedUp.timeInterval = params.row.earlyUrgentPay
            this.tBindForm.speedUp.urgentTime = params.row.lastUrgentPay
            this.tBindForm.speedUp.urgents = params.row.urgentPay
              ? params.row.urgentPay.split(',')
              : ['']
            this.tBindForm.timePeriod = params.row
              .canAppointmentTime
              ? JSON.parse(params.row.canAppointmentTime)
              : [
                {
                  startTime: '',
                  entTime: '',
                  extraCharge: 0
                }
              ]
            this.tBindForm.fastTime = params.row.sendFastestTime
            this.tBindForm.slowTime = params.row.sendSlowestTime
            console.log(this.tBindForm.distributionArea.support)
            break
          default:
            break
        }
      }
    },
    /** 添加时间段 */
    handelAddTime() {
      this.tBindForm.timePeriod.push({
        startTime: '',
        entTime: '',
        extraCharge: ''
      })
    },
    /** 是否加急处理 */
    handelCheckChange(v) {
      console.log(v)
      // this.tBindForm.billingMethod = (parseInt(v) + 1).toString()
    },
    handelFormSubmitk(key) {
      this.$refs.formsk.validate(v => {
        if (v) {
          this.updateEdit(key)
        } else {
          this.butloading = false
        }
      })
    },
    handelFormSubmitt(key) {
      this.$refs.formst.validate(v => {
        if (v) {
          this.updateEdit(key)
        } else {
          this.butloading = false
        }
      })
    },
    updateEdit(key) {
      const params = this.$dd(this.$route.query.p)
      this.butloading = true
      switch (key) {
        case 'K':
          this.kBindForm.bistributionArea.forEach(inf => {
            inf.region = inf.region.toString()
          })
          if (
            params.activeModel === '1' &&
            params.status === 'add'
          ) {
            FreightTemplateAdd(this.kBindForm)
              .then(inf => {
                this.butloading = false
                this.$store.dispatch('tagsView/delView', this.$route)
                this.$message.success('成功添加')
                this.$router.go(-1)
              })
              .catch(() => {
                this.butloading = false
              })
            return
          }
          if (
            params.activeModel === '1' &&
            params.status === 'edit'
          ) {
            this.kBindForm.templateID = params.templateID
            FreightTemplatekEdit(this.kBindForm)
              .then(() => {
                this.butloading = false
                this.$store.dispatch('tagsView/delView', this.$route)
                this.$message.success('编辑成功')
                this.$router.go(-1)
              })
              .catch(() => {
                this.butloading = false
              })
          } else {
            FreightTemplateAdd(this.kBindForm)
              .then(inf => {
                this.butloading = false
                this.$store.dispatch('tagsView/delView', this.$route)
                this.$message.success('成功添加')
                this.$router.go(-1)
              })
              .catch(() => {
                this.butloading = false
              })
          }
          break
        case 'T':
          this.tBindForm.speedUp.urgent = this.tBindForm.speedUp.urgents.toString()
          if (
            params.activeModel === '2' &&
            params.status === 'add'
          ) {
            const data = this.$XEUtils.clone(this.tBindForm, true)
            if (data.weight.type == '0') {
              data.weight.extra = data.weight.weightExtra
              data.weight.addCharges = data.weight.weightAddCharges
              data.weight.increase = data.weight.weightIncrease
            } else if (data.weight.type == '1') {
              data.weight.extra = data.weight.pieceExtra
              data.weight.addCharges = data.weight.pieceAddCharges
              data.weight.increase = data.weight.pieceIncrease
            }
            delete data.weight.weightExtra
            delete data.weight.weightIncrease
            delete data.weight.weightAddCharges
            delete data.weight.pieceExtra
            delete data.weight.pieceIncrease
            delete data.weight.pieceAddCharges
            addSameCityAdd(data)
              .then(() => {
                this.butloading = false
                this.$store.dispatch('tagsView/delView', this.$route)
                this.$message.success('成功添加')
                this.$router.go(-1)
              })
              .catch(() => {
                this.butloading = false
              })
            return
          }
          if (
            params.activeModel === '2' &&
            params.status === 'edit'
          ) {
            this.kBindForm.templateID = params.templateID
            const data = this.$XEUtils.clone(this.tBindForm, true)
            if (data.weight.type == '0') {
              data.weight.extra = data.weight.weightExtra
              data.weight.addCharges = data.weight.weightAddCharges
              data.weight.increase = data.weight.weightIncrease
            } else if (data.weight.type == '1') {
              data.weight.extra = data.weight.pieceExtra
              data.weight.addCharges = data.weight.pieceAddCharges
              data.weight.increase = data.weight.pieceIncrease
            }
            delete data.weight.weightExtra
            delete data.weight.weightIncrease
            delete data.weight.weightAddCharges
            delete data.weight.pieceExtra
            delete data.weight.pieceIncrease
            delete data.weight.pieceAddCharges
            FreightTemplatetEdit(data)
              .then(() => {
                this.butloading = false
                this.$store.dispatch('tagsView/delView', this.$route)
                this.$message.success('编辑成功')
                this.$router.go(-1)
              })
              .catch(() => {
                this.butloading = false
              })
          } else {
            const data = this.$XEUtils.clone(this.tBindForm, true)
            if (data.weight.type == '0') {
              data.weight.extra = data.weight.weightExtra
              data.weight.addCharges = data.weight.weightAddCharges
              data.weight.increase = data.weight.weightIncrease
            } else if (data.weight.type == '1') {
              data.weight.extra = data.weight.pieceExtra
              data.weight.addCharges = data.weight.pieceAddCharges
              data.weight.increase = data.weight.pieceIncrease
            }
            delete data.weight.weightExtra
            delete data.weight.weightIncrease
            delete data.weight.weightAddCharges
            delete data.weight.pieceExtra
            delete data.weight.pieceIncrease
            delete data.weight.pieceAddCharges
            addSameCityAdd(data)
              .then(() => {
                this.butloading = false
                this.$store.dispatch('tagsView/delView', this.$route)
                this.$message.success('成功添加')
                this.$router.go(-1)
              })
              .catch(() => {
                this.butloading = false
              })
          }
          break
      }
    },
    /** select change */
    handelChange(val) {
      this.selectCheck = val
    },
    handelBefore(done) {
      this.selectCheck = []
      done()
    },
    /** dialog 确定 */
    handelSubmit() {
      var list = []
      let isTrue = false
      var str = ''
      if (this.selectCheck.length > 0) {
        if (this.isTrue) {
          this.kBindForm.bistributionArea.forEach(reg => {
            reg.region.forEach(isf => {
              this.selectCheck.forEach(ins => {
                if (isf.toString() === ins.toString()) {
                  isTrue = true
                  str += `${
                    this.options.find(
                      inf => inf.id.toString() === ins.toString()
                    ).name
                  } `
                }
              })
            })
          })
        } else {
          this.kBindForm.bistributionArea.forEach((reg, index) => {
            if (index > 0) {
              if (this.index >= 1) {
                this.kBindForm.bistributionArea[
                  index - 1 !== this.index ? index - 1 : index
                ].region.forEach(isf => {
                  this.selectCheck.forEach(ins => {
                    if (isf.toString() === ins.toString()) {
                      isTrue = true
                      str += `${
                        this.options.find(
                          inf => inf.id.toString() === ins.toString()
                        ).name
                      } `
                    }
                  })
                })
              } else {
                this.kBindForm.bistributionArea[index].region.forEach(isf => {
                  this.selectCheck.forEach(ins => {
                    if (isf.toString() === ins.toString()) {
                      isTrue = true
                      str += `${
                        this.options.find(
                          inf => inf.id.toString() === ins.toString()
                        ).name
                      } `
                    }
                  })
                })
              }
            }
          })
        }
        if (isTrue) {
          this.$confirm('城市:' + str + '已被使用', '提示', {
            cancelButtonText: '确定',
            cancelButtonClass: '取消',
            type: 'info'
          })
          str = ''
          return
        } else {
          this.options.forEach(inf => {
            this.selectCheck.forEach(res => {
              if (inf.id.toString() === res.toString()) {
                list.push(inf.name)
              }
            })
          })
        }
      } else {
        this.$message.warning('请选择配送区域')
        return
      }
      if (this.isTrue) {
        this.kBindForm.bistributionArea.push({
          addressName: list.toString(),
          region: this.selectCheck,
          theFirstPiece: '',
          piece: '',
          ahead: '',
          charge: ''
        })
      } else {
        this.kBindForm.bistributionArea[
          this.index
        ].addressName = list.toString()
        this.kBindForm.bistributionArea[this.index].region = this.selectCheck
      }
      this.pcaList = list.toString()
      this.selectCheck = []
      this.visible = false
    },
    /** 修改配送区域对话框 */
    handelUpdateArea(index) {
      console.log(this.kBindForm.bistributionArea[index].region)
      const type = typeof this.kBindForm.bistributionArea[index].region
      if (type === 'string') {
        this.kBindForm.bistributionArea[index].region = this.kBindForm.bistributionArea[index].region.split(',')
      }
      this.index = index
      this.selectCheck = this.kBindForm.bistributionArea[index].region
      this.province = this.kBindForm.bistributionArea[index].region.map(Number)
      this.visible = true
      this.isTrue = false
    },
    handelDel(index) {
      this.province = []
      this.kBindForm.bistributionArea.splice(index, 1)
    },
    /** 添加配送区域对话框 */
    handelAddArea() {
      this.province = []
      this.getCity(false)
      this.visible = !this.visible
      this.isTrue = true
    },
    getCity(val) {
      this.options = []
      this.seloading = true
      getCityList().then(res => {
        console.log(res.data.data)
        res.data.data.forEach(inf => {
          this.options.push({
            id: inf.province.id,
            name: inf.province.name
          })
        })
        if (val) {
          this.loadding()
        }
        this.seloading = false
        console.log(this.tBindForm.distributionArea.support)
      })
    },
    slowTime(rules, value, collback) {
      if (this.tBindForm.fastTime <= value) {
        collback()
      } else {
        collback(new Error('最慢送达时间不能小于最快送达时间'))
      }
    },
    vastartTime(rules, value, collback) {
      if (rules.index > 0 && value) {
        if (
          parseInt(value.replace(':', '')) >=
          parseInt(
            this.tBindForm.timePeriod[rules.index - 1].entTime.replace(':', '')
          )
        ) {
          collback()
        } else {
          collback(new Error(`当前时间段要大于时间段${rules.index}`))
        }
      } else {
        collback()
      }
    }
  }
  /* beforeRouteEnter(to, from, next) {
    // ...
    if (to.query.activeModel === '1' && to.query.status === 'edit') {
      to.meta.title = '编辑快递'
    } else if (to.query.activeModel === '2' && to.query.status === 'edit') {
      to.meta.title = '编辑同城'
    } else if (to.query.activeModel === '2' && to.query.status === 'copy') {
      to.meta.title = '新增运费模板'
    } else if (to.query.activeModel === '1' && to.query.status === 'copy') {
      to.meta.title = '新增运费模板'
    } else {
      to.meta.title = '新增运费模板'
    }
    next()
  },
  beforeRouteLeave(to, from, next) {
    this.$store.dispatch('tagsView/delView', from)
    next()
  }*/
}
</script>

<style lang="scss" scoped>
.AddFreightModel {
  padding: 50px 100px;
  .tabspane {
    ::v-deep.el-form {
      margin-top: 40px;
      .el-form-item__label {
        width: 100px;
        text-align: start;
      }
      .templateName {
        .el-form-item__error {
          margin-left: 100px;
        }
      }
      .el-form-item {
        .el-input {
          width: 200px;
        }
        .el-input-number {
          width: 100px;
        }
        .cus-area {
          display: flex;
          align-items: center;
          justify-content: space-between;
          flex-wrap: wrap;
          .left,
          .right {
            flex-grow: 1;
            .el-form-item__error {
              margin-left: 25px;
            }
          }
          .left {
            .addressName {
              display: inline-block;
              width: 400px;
              overflow-wrap: break-word;
            }
            p {
              padding: 0px 20px;
            }
            p:last-child {
              display: flex;
              justify-content: space-between;
            }
          }
          .right {
            table {
              width: 100%;
            }
            tr {
              text-align: center;
              td {
                .el-input {
                  width: 100px;
                }
              }
            }
          }
        }
        .cus-btn-footer {
          margin-top: 40px;
        }
        .cus-btn-submit {
          width: 100%;
          margin-top: 40px;
          .el-button {
            width: 200px;
            margin: 0px auto;
            margin-left: 40%;
          }
        }
      }
      .cus-footer {
        width: 100%;
        margin-bottom: 0;
        .cus-btn-submit {
          width: 200px;
          height: 50px;
          margin-left: 40%;
        }
      }
      .JFFS {
        color: gray;
      }
      .PSQY,
      .XZSF {
        width: 100%;
        display: flex;
        align-items: center;
        margin-bottom: 30px;
        .el-form-item__error {
          margin-left: 10px;
        }
        .distributionArea {
          .el-form-item__error {
            margin-left: 70px;
          }
        }
        p {
          margin: 0;
          .el-input {
            width: 100px;
            padding: 0px 10px;
          }
        }
        p:last-child {
          margin-left: 30px;
        }
      }
      .PSFS {
        .YYTS {
          margin: 10px 0px;
          span {
            display: inline-block;
          }
          span:first-child {
            width: 60px;
          }
          .title-yyts {
            width: 100px !important;
          }
          .mleft {
            margin-left: 10px;
          }
          p {
            color: gray;
            margin-top: 0;
            margin-left: 100px;
          }
          .el-time-select {
            margin: 0px 10px;
          }
          position: relative;
          .JSAOa {
            padding: 0;
            margin: 0;
            line-height: 20px;
            color: black;
            position: absolute;
            z-index: 1000;
            width: 45%;
            right: 0;
            top: 0;
          }
          .JSAOb {
            color: black;
            position: absolute;
            z-index: 1000;
            width: 45%;
            right: 0;
            top: 32px;
          }
        }
        .SHDUAN {
          margin: 20px 0px;
          display: flex;
          flex-wrap: wrap;
          .left {
            display: flex;
            flex-wrap: wrap;
            span {
              display: inline-block;
            }
            .title-yyts {
              width: 100px;
            }
            .ewfy {
              min-width: 200px;
              .inputNumber {
                .el-input__inner {
                  width: 100px;
                }
              }
            }
            .mleft {
              margin: 0px 10px;
            }
          }
          .add_button {
            margin-left: 105px;
          }
          .el-form-item__error {
            margin-left: 113px;
          }
        }
      }
      .MapArea {
        width: 100%;
        .baidu-map {
          width: 100%;
          height: 600px;
        }
      }
    }
  }

  .ele-select {
    width: 100% !important;
    .el-input {
      width: 100% !important;
    }
  }
}
</style>
